package com.sky.utils;

import com.alibaba.fastjson.JSONObject;
import com.sky.properties.BaiduMapProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class BaiduMapUtil {
    @Autowired
    /**
     * 计算两地距离工具类
     */
    private BaiduMapProperties bmp;
    //"长沙市高新区东方红中路368号"
    public   Integer getDistance(String shopAddress,String shopCity,String dest,String destCity){
        String origin = getGeoCoding(shopAddress, shopCity, bmp.getBaiduAPK(), "json");
        String destination = getGeoCoding(dest, destCity, bmp.getBaiduAPK(), "json");
        System.out.println(origin);
        System.out.println(destination);
        Integer distance = getDis(origin, destination, bmp.getBaiduAPK());
        return distance;
    }
    //获得两地距离
    private Integer getDis(String origin,String destination,String ak){
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("origin", origin);
        paramMap.put("destination", destination);
        paramMap.put("ak", ak);
        String body = HttpClientUtil.doGet(bmp.getDrivingDirectionliteUrl(), paramMap);
        JSONObject jsonObject = (JSONObject) JSONObject.parseObject(body).getJSONObject("result").getJSONArray("routes").get(0);
        Integer distance = jsonObject.getInteger("distance");
        System.out.println(distance);
        return distance;
    }
    //拿到经纬度
    private String getGeoCoding(String address,String city,String ak,String output){
        Map<String,String> paramMap = new HashMap<>();
        paramMap.put("address", address);
        paramMap.put("city", city);
        paramMap.put("ak", ak);
        paramMap.put("output", output);
        String body = HttpClientUtil.doGet(bmp.getGeocodingUrl(), paramMap);
        JSONObject jsonObject = JSONObject.parseObject(body);
        String result = jsonObject.getString("result");
        JSONObject jo = JSONObject.parseObject(result);
        String lat = jo.getJSONObject("location").getString("lat");  //维度
        String lng = jo.getJSONObject("location").getString("lng");   //经度
        return lat + "," + lng ;
    }

}
